package com.servicesystem.servicesystem.untis;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author X
 * @version 1.0
 * @ClassName Http
 * @description
 * @date 2020/9/9
 **/
public class Http{

    public String doGet(String url){
        String result = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            //创建HttpClient对象
            httpClient = HttpClients.createDefault();
            //创建HttpGet对象
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)//设置连接超时时间
                    .setConnectionRequestTimeout(30000)//从连接池获取连接超时时间
                    .setSocketTimeout(30000)//设置读取数据超时时间
                    .build();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("返回结果："+result);
        return result;
    }
}
